<template>
  <div>
    <el-popover ref="popover" placement="bottom" width="200" trigger="click">
      <el-input
        slot="reference"
        v-model="value"
        :maxlength="props.maxlength"
        :show-word-limit="props.maxlength > 0"
        v-on="$listeners"
      />
      <el-tree
        ref="tree"
        class="filter-tree"
        :data="treeData"
        :props="props"
        default-expand-all
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      ></el-tree>
    </el-popover>
  </div>
</template>
<script>
export default {
  name: 'ElTreeAutocomplete',
  model: {
    prop: 'defaultValue',
    event: 'change'
  },
  props: {
    props: {
      type: Object,
      default() {
        return {}
      }
    }, // 父组件传的值
    defaultValue: {
      type: [String, Number],
      default: undefined
    }, // 绑定的默认值
    treeData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return { value: '' }
  },
  watch: {
    defaultValue(val) {
      this.value = val
    },
    value(val) {
      if (this.props.filterable) {
        this.$refs.tree.filter(val)
      }
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data[this.props.label].indexOf(value) !== -1
    },
    handleNodeClick(item) {
      if (!item[this.props.children] || item[this.props.children].length === 0) {
        this.$refs.popover.doClose()
        this.$emit('change', item[this.props.value])
      }
    }
  }
}
</script>
<style lang="less" scoped></style>
